import React from 'react'
import menuRoute from 'routes/menuRoute'

import { connect } from 'react-redux'
import constants from 'share/constants'
import configureStore from "stores";
import classNames from 'classnames';
import CustomTable from 'components/custom-table'
import { setApproveRequest, setApproveExpenseReport } from "actions/cache";
import { messages, deepFullCopy, dealCache } from "share/common";
import { Form, Badge, Popover, Table, Affix, message, Button, } from 'antd'
import moment from 'moment'
import SearchArea from 'components/search-area'
import ApproveBar from 'components/template/approve-bar'
import 'styles/approve/request/request.scss'
import 'styles/setting/process-monitoring-platform/process-monitoring-platform.scss'
import AdminSkip from 'containers/setting/process-monitoring-platform/admin-skip/admin-skip'
import adminApproveListService from 'containers/setting/process-monitoring-platform/admin-approve-list.service'
import Condition from 'components/condition'
const { If, ElseIf, Else } = Condition;
import ResizeTable from "components/resize-table";

class AdminApproveList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      passLoading: false,
      rejectLoading: false,
      searchForm: [
        {
          type: 'select', options: [
          {
            value: 2001,
            label: messages('setting.key847'/*报销单*/) //报销单
          }, {
            value: 1002,
            label: messages('setting.key848'/*差旅申请单*/)  //差旅
          }, {
            value: 1001,
            label: messages('setting.key849'/*费用申请单*/) //费用
          }, {
            value: 1003,
            label: messages('setting.key850'/*订票申请单*/) //订票
            // }, {
            //   value: 2004,
            //   text: messages('documentType.jd.request') //京东
          }, {
            value: 2005,
            label: messages('setting.key1593')/*单行借款单*///messages('setting.key851'/*借款申请单*/) //借款
          }
        ], id: 'formType', label: messages('setting.key852'/*单据类*/)
        },
        {
          type: 'list',
          id: 'approverOIDs',
          label: messages('setting.key853'/*当前审批人*/),
          listType: 'user',
          labelKey: 'fullName',
          valueKey: 'userOID',
          listExtraParams: {
            roleType: !props.tenantMode ? '' : 'TENANT',
            status: 'all',
            companyOID: props.tenantMode ? null : props.company.companyOID
          }
        },
        { type: 'input', id: 'businessCode', label: messages('setting.key854'/*单号*/) },
        {
          type: 'list',
          id: 'applicantOIDs',
          label: messages('setting.key855'/*申请人*/),
          listType: 'user',
          labelKey: 'fullName',
          valueKey: 'userOID',
          listExtraParams: {
            roleType: !props.tenantMode ? '' : 'TENANT',
            status: 'all',
            companyOID: props.tenantMode ? null : props.company.companyOID
          }
        },
        {
          type: 'list',
          id: 'departmentOIDs',
          label: messages('setting.key856'/*部门*/),
          listType: 'department',
          labelKey: 'name',
          valueKey: 'departmentOid',
          single: true
        },
        {
          type: 'items', id: 'priceRange', items: [
          { type: 'inputNumber', id: 'minAmount', label: messages('setting.key857'/*金额从*/) },
          { type: 'inputNumber', id: 'maxAmount', label: messages('setting.key858'/*金额至*/) }
        ]
        },
        {
          type: 'items', id: 'dateRange', items: [
          {
            type: 'date',
            id: 'beginDate',
            label: messages('setting.key859'/*日期从*/),
            defaultValue: moment().subtract(1, 'months')
          },
          {
            type: 'date',
            id: 'endDate',
            label: messages('setting.key860'/*日期至*/),
            defaultValue: moment(new Date())
          }
        ]
        }
      ],
      approvePendingSearchParams: {
        beginDate: moment().subtract(1, 'months').format('YYYY-MM-DD'),
        endDate: moment(new Date()).format('YYYY-MM-DD')
      },

      status: [
        { label: messages('setting.key861'/*编辑中*/), value: '10011000', state: 'processing' },
        { label: messages('setting.key862'/*已撤回*/), value: '10011001', state: 'warning' },
        { label: messages('setting.key863'/*已驳回*/), value: '10011002', state: 'error' },
        { label: messages('setting.key864'/*审核驳回*/), value: '10011003', state: 'error' },
        { label: messages('setting.key865'/*审批中*/), value: '10021000', state: 'processing' },
        { label: messages('setting.key866'/*已通过*/), value: '10031000', state: 'success' },
        { label: messages('setting.key867'/*审核通过*/), value: '1004', state: 'success' },
        { label: messages('setting.key868'/*已付款*/), value: '1005', state: 'success' },
        { label: messages('setting.key869'/*还款中*/), value: '1006', state: 'processing' },
        { label: messages('setting.key870'/*已还款*/), value: '1007', state: 'success' },
        { label: messages('setting.key871'/*付款中*/), value: '1008', state: 'processing' },
        { label: messages('setting.key872'/*已停用*/), value: '1009', state: 'default' }
      ],
      tableOption: {
        rowKey: 'entityOID'
      },
      columns: [
        {
          title: messages('common.sequence'/*序号*/), dataIndex: 'index', width: 48, render: (value, record, index) =>
          (index + 1 + this.state.pageSize * this.state.page)
        },
        {
          title: messages('setting.key873'/*工号*/), dataIndex: 'employeeID', width: '6%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key855'/*申请人*/),
          dataIndex: 'applicantName',
          width: '8%',
          render: value =>
            (value && value) ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key874'/*提交日期*/),
          dataIndex: 'submittedDate',
          sorter: true,
          width: 120,
          render: value => moment(value).format('YYYY-MM-DD')
        },
        {
          title: messages('setting.key875'/*单据名称*/), dataIndex: 'formName', width: '10%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key854'/*单号*/),
          dataIndex: 'businessCode',
          width: '9%',
          render: value =>
            value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('setting.key876'/*事由*/), dataIndex: 'title', width: '10%', render: value =>
          value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        { title: messages('setting.key877'/*币种*/), width: '5%', dataIndex: 'baseCurrency' },
        {
          title: messages('setting.key878'/*金额*/),
          width: '10%',
          dataIndex: 'totalAmount',
          sorter: true,
          render: value => value ? this.filterMoney(value) : <span className="money-cell">-</span>
        },
        {
          title: messages('common.column.status'),
          dataIndex: 'status',
          width: this.props.language.code === 'zh_cn' ? '8%' : '10%',
          render: (value, record) => {
            return (
              <Badge text={constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus') ||
              constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus') ||
              constants.getTextByValue(String(value), 'documentStatus')}
                     status={constants.getTextByValue(String(value + '' + record.applicationType), 'documentStatus', 'state') ||
                     constants.getTextByValue(String(value + '' + record.rejectType), 'documentStatus', 'state') ||
                     constants.getTextByValue(String(value), 'documentStatus', 'state')}/>
            )
          }
        },
        {
          title: messages('setting.key853')/*当前审批人*/,
          dataIndex: 'approvalChains',
          width: '10%',
          render: values => (
            <Popover content={values.map(value => value.approverName + ' ')}>
              {values.map(value => <span key={value.approverOID}>{value.approverName + ' '}</span>)}
            </Popover>
          ),
        },
        {
          title: messages('common.operation')/*操作*/,
          width: 50,
          dataIndex: 'operation',
          render: (value, record, index) => {
            return (
              <div>
                <If value={record.approvalMode === 1005}>
                  <a className="btn-class" onClick={e => this.adminOperationSkip(e, record)}
                     type="primary">{messages('setting.key879'/*跳转*/)}</a>
                </If>
                {
                  record.hasClicked ? <a onClick={e => { e.stopPropagation()}}
                                         className="btn-class-gray">{messages('setting.key1707')/*催办*/}</a> :
                    <a className="btn-class"
                       onClick={e => this.handlePress(e, record, index)}>{messages('setting.key1707')/*催办*/}</a>
                }
              </div>
            )
          }
        }
      ],
      sort: '',
      dataSource: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      },
      batchEnabled: false, //是否有批量审批
      selectedRowKeys: [],
      selectedRows: [], //选中的单据OID
      cacheSearchData: {}, //缓存筛选的数据
      approveRequestDetail: menuRoute.getRouteItem('admin-approve-request-detail', 'key'), //申请单审批详情页
      approveExpenseReportDetail: menuRoute.getRouteItem('admin-approve-expense-detail', 'key'), //报销单审批详情页
      approveLoanDetail: menuRoute.getRouteItem('admin-approve-loan-detail', 'key'), //借款单审批详情页
      showAdminSkipModal: false,//显示跳转弹框
      currentSkipItem: {},
    }
  }

  componentDidMount() {
    this.setState({
      batchEnabled: this.props.profile['all.Approval.batch.Enable']
    }, () => {
      this.getCache();
    })
  }

  //管理员跳转
  adminOperationSkip = (e, record) => {
    e.stopPropagation();
    if (record.version && record.version.split('.')[0] > 0) {
      this.setState({
        showAdminSkipModal: true,
        isNew: true,
        currentSkipItem: record,
      })
    } else {
      this.setState({
        showAdminSkipModal: true,
        isNew: false,
        currentSkipItem: record,
      })
    }
  };

  //催办
  handlePress = (e, record, index) => {
    e.stopPropagation();
    const { dataSource }  = this.state;
    dataSource[index].hasClicked = true;
    this.setState({ dataSource });
    let params = {
      "approverOID": record.approverOID,
      "entityOID": record.entityOID,
      "entityType": record.entityType,
      applicantOID: record.applicantOID,
      businessCode: record.businessCode,
      formOID: record.formOID
    }
    adminApproveListService.postPressMessage(params)
      .then(res => {
        if (res.data) {
          message.info(messages('setting.key1708')/*已向审批人发出催办消息*/);
          setTimeout(() => {
            dataSource[index].hasClicked = false;
            this.setState({ dataSource })
          }, 3000)
        }
      }).catch(e => {
      this.setState({ loading: false });
      message.error(`${e.response.data.message}`)
    });

  }

  //存储筛选数据缓存
  setCache = (result) => {
    const { page } = this.state;
    result.page = page;
    this.setState({ cacheSearchData: result })
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.approveRequest;
    if (result && JSON.stringify(result) !== "{}") {
      this.setState({ cacheSearchData: result }, () => {
        this.dealCache(result)
      })
    }
    else {
      let defaultSearchForm = deepFullCopy(this.state.searchForm);
      this.getList();
      this.setState({ defaultSearchForm })
    }
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const { searchForm } = this.state;
    let defaultSearchForm = deepFullCopy(this.state.searchForm);
    if (result) {
      dealCache(searchForm, result);
      this.setState({
        page: result.page,
        defaultSearchForm
      }, () => {
        this.search(result);
        configureStore.store.dispatch(setApproveRequest(null));
      })
    }
  };

  getList = () => {
    const { page, pageSize, approvePendingSearchParams, sort, cacheSearchData } = this.state;
    cacheSearchData.sort = sort;
    approvePendingSearchParams.sort = sort;
    this.setCache(approvePendingSearchParams);
    this.setState({ loading: true });
    if (!this.props.tenantMode) {
      approvePendingSearchParams.companyOID = this.props.company.companyOID;
    }
    adminApproveListService.getAdminApproveList(page, pageSize, approvePendingSearchParams).then(res => {
      let dataSource = [];
      res.data.map(item => {
        if (item.expenseReport) {
          item.expenseReport.approvalMode = item.approvalMode;
          item.expenseReport.entityType = item.entityType;
          item.expenseReport.entityOID = item.entityOID;
          item.expenseReport.submittedDate = item.expenseReport.lastSubmittedDate;
          item.expenseReport.baseCurrencyAmount = item.expenseReport.totalAmount;
          item.expenseReport.baseCurrency = item.expenseReport.currencyCode;
          item.expenseReport.currentNodeOID = item.expenseReport.approvalChains[0].ruleApprovalNodeOID;
          item.expenseReport.version = item.expenseReport.approvalChains[0].version;
          dataSource.push(item.expenseReport || {})
        }
        if (item.application) {
          item.application.approvalMode = item.approvalMode;
          item.application.entityType = item.entityType;
          item.application.entityOID = item.entityOID;
          item.application.baseCurrencyAmount = item.application.originCurrencyTotalAmount;
          item.application.baseCurrency = item.application.originCurrencyCode;
          item.application.currentNodeOID = item.application.approvalChains[0].ruleApprovalNodeOID;
          item.application.version = item.application.approvalChains[0].version;
          dataSource.push(item.application || {})
        }
        if (item.loanBill) {
          item.loanBill.approvalMode = item.approvalMode;
          item.loanBill.entityType = item.entityType;
          item.loanBill.entityOID = item.entityOID;
          item.loanBill.employeeID = item.loanBill.applicant.employeeID;
          item.loanBill.applicantName = item.loanBill.applicant.fullName;
          // item.employeeID = item.applicant.employeeID;
          item.loanBill.totalAmount = item.loanBill.baseCurrencyAmount;
          item.loanBill.baseCurrency = item.loanBill.baseCurrencyCode;
          item.loanBill.currentNodeOID = item.loanBill.approvalChains[0].ruleApprovalNodeOID;
          item.loanBill.version = item.loanBill.approvalChains[0].version;
          dataSource.push(item.loanBill || {})
        }
      });
      this.setState({
        loading: false,
        dataSource,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          current: page + 1,
          onChange: this.onChangePaper
        }
      })
    })
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        const { approvePendingSearchParams, } = this.state;
        this.setCache(approvePendingSearchParams);
        //this.getList()
      })
    }
  };


  search = (values) => {
    values.formTypeOption && delete values.formTypeOption;
    values.formTypeLable && delete values.formTypeLable;
    this.setCache({ ...values });
    values.beginDate && (values.beginDate = moment(values.beginDate).format('YYYY-MM-DD'));
    values.endDate && (values.endDate = moment(values.endDate).format('YYYY-MM-DD'));
    this.setState({
      approvePendingSearchParams: values,
      page: 0,
      pagination: { total: 0 }
    }, () => {
      this.getList()
    })
  };

  searchClear = () => {
    this.setState({ cacheSearchData: {}, clearAll: true });
    this.setCache({});
    let { defaultSearchForm }=this.state;
    defaultSearchForm[6].items.map(item => {
      item.defaultValue = null;
    });
    this.setState({
      approvePendingSearchParams: {},
      page: 0,
      searchForm: deepFullCopy(defaultSearchForm),
      pagination: { total: 0 }
    }, () => {
      this.getList()
    })
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let sort = '';
    if (sorter.order) {
      sort = `${sorter.columnKey},${sorter.order === 'ascend' ? 'ASC' : 'DESC'}`
    }
    this.setState({
      page: page - 1,
      sort
    }, () => {
      this.getList();
    });
  };

  handleRowClick = (record) => {
    //申请单
    if (record.entityType === 1001) {
      configureStore.store.dispatch(setApproveRequest(this.state.cacheSearchData));
      let url = this.state.approveRequestDetail.url.replace(':formOID', record.formOID).replace(':applicationOID', record.applicationOID);
      url += `?approving=true&approverOID=${record.approverOID}&approvalMode=${record.approvalMode}`;
      this.context.router.push(url)
    } else if (record.entityType === 1002) {
      //报销单
      configureStore.store.dispatch(setApproveRequest(this.state.cacheSearchData));
      let url = this.state.approveExpenseReportDetail.url.replace(':expenseReportOID', record.entityOID);
      url += `?approvePending=true&approverOID=${record.approverOID}&approvalMode=${record.approvalMode}`;
      this.context.router.push(url);
    } else if (record.entityType === 3001) {
      //借款申请单
      configureStore.store.dispatch(setApproveRequest(this.state.cacheSearchData));
      let url = this.state.approveLoanDetail.url.replace(':formOID', record.formOID).replace(':loanBillOID', record.loanBillOID);
      url += `?approving=true&approverOID=${record.approverOID}&approvalMode=${record.approvalMode}`;
      this.context.router.push(url)
    }
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length > 20) {
      message.warning(messages('setting.key880'/*最多选择20条数据*/))
    } else {
      this.setState({ selectedRowKeys })
    }
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let item = JSON.stringify({
      approverOID: record.approverOID,
      entityOID: record.entityOID,
      entityType: record.entityType,
    });
    selected ? selectedRows.push(item) : selectedRows.delete(item);
    selectedRows.length <= 20 && this.setState({ selectedRows })
  };

  //全选
  onSelectAllRow = (selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    this.state.dataSource.map(item => {
      let row = JSON.stringify({
        approverOID: item.approverOID,
        entityOID: item.entityOID,
        entityType: item.entityType,
      });
      selected ? selectedRows.addIfNotExist(row) : selectedRows.delete(row);
    });
    selectedRows.length <= 20 && this.setState({ selectedRows })
  };

  //审批操作
  handleApprove = (value, type) => {
    let entities = [];
    this.state.selectedRows.map(item => {
      entities.push(JSON.parse(item))
    });
    let params = {
      entities,
      approvalTxt: value
    };
    this.setState({ [type === 'pass' ? 'passLoading' : 'rejectLoading']: true });
    adminApproveListService[type === 'pass' ? 'handleRequestApprovePass' : 'handleRequestApproveReject'](params).then(res => {
      if (res.status === 200) {
        message.success(messages('setting.key1464', { arg1: res.data.successNum }/*成功处理 {arg1} 笔单据*/) +
          messages('setting.key1465', { arg1: res.data.failNum }/*失败 {arg1} 笔单据*/));
        this.setState({ passLoading: false, rejectLoading: false });
        this.setState({
          page: 0,
          pagination: { total: 0 },
          selectedRowKeys: [],
          selectedRows: [],
        }, () => {
          this.getList()
        })
      }
    }).catch(e => {
      this.setState({ passLoading: false, rejectLoading: false });
      message.error(`${messages('common.operate.filed'/*操作失败*/)}，${e.response.data.message}`)
    })
  };


  afterClose = res => {
    this.setState({
      showAdminSkipModal: false,
    }, () => {
      res === 'success' && this.getList();
      // this.getForms()
    })
  };


  render() {
    const {
      loading, searchForm,
      columns, dataSource, pagination, batchEnabled, selectedRowKeys, selectedRows,
      passLoading, rejectLoading, showAdminSkipModal, currentSkipItem, isNew
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };
    return (
      <div
        className={`approve-request ${selectedRows.length ? 'bottom-100 process-monitoring-platform' : 'process-monitoring-platform'}`}>
        <AdminSkip
          title={messages('setting.key881'/*跳转至*/)}
          entityOID={currentSkipItem.entityOID}
          entityType={currentSkipItem.entityType}
          currentNodeOID={currentSkipItem.currentNodeOID}
          onOk={this.handleOkTemp}
          formOID={currentSkipItem.formOID}
          version={currentSkipItem.version}
          afterClose={this.afterClose}
          fromList
          isNew={isNew}
          visible={showAdminSkipModal}
        />
        <SearchArea searchForm={searchForm}
                    isReturnLabel
                    maxLength={8}
                    submitHandle={this.search}
                    clearHandle={this.searchClear}/>
        <div className="table-header">
          <div className="table-header-title">
            {messages('common.total', { total: pagination.total }/*共搜索到 {total} 条数据*/)}
            { batchEnabled && ` / ${messages('common.total.selected', { total: selectedRows.length })/*已选 {total} 条*/}`}
          </div>
        </div>
        <ResizeTable
          columns={columns}
          {...{
            rowKey: 'entityOID',
            size: 'middle',
            loading,
            rowSelection,
            pagination,
            columns,
            onChange: this.handleTableChange,
            onRow: record => ({
            onClick: () => this.handleRowClick(record)
          }),
            bordered: true,
            dataSource
          }}
        />
        <Affix offsetBottom={0} className={`bottom-bar-approve ${selectedRows.length ? 'show' : 'hide'}`}>
          <ApproveBar
            passLoading={passLoading}
            admin
            buttons={['pass', 'reject']}
            rejectLoading={rejectLoading}
            batchNumber={selectedRows.length}
            handleApproveSkip={this.afterClose}
            handleApprovePass={value => this.handleApprove(value, 'pass')}
            handleApproveReject={value => this.handleApprove(value, 'reject')}
          />
        </Affix>
      </div>
    )
  }
}

AdminApproveList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    language: state.main.language,
    approveRequest: state.cache.approveRequest,
    tenantMode: state.main.tenantMode,
    company: state.login.company,
  }
}

const wrappedAdminApproveList = Form.create()(AdminApproveList);

export default connect(mapStateToProps)(wrappedAdminApproveList)
